import {Injectable, ViewContainerRef} from '@angular/core';
import {Event, NavigationEnd, Router} from "@angular/router";
import {HeaderService} from "./application/common/header/header.service";
import {EventEmitter} from "./support/event";
import {noop} from "./support/noop";

@Injectable({providedIn: 'root'})
export class AppService {

  // 全局事件管理
  private event: EventEmitter = new EventEmitter();
  private viewContainerRef: ViewContainerRef;
  public space: any = {title: "归园田居的工作区"};
  isLogin: boolean = false;

  constructor(private router: Router, public header: HeaderService) {
    // 全局事件监听
    this.router.events.subscribe((event: Event) => {
      if (event instanceof NavigationEnd) {
        // this.url.reset(router);
      }
    });
  }

  // 订阅事件
  subscribe(events, callback?): Function {
    if (events instanceof Array) {
      events.forEach(eventName => this.event.subscribe(eventName, callback));
      return noop
    } else if (events instanceof Object) {
      Object.keys(events).forEach(eventName => this.event.subscribe(eventName, events[eventName]));
      return noop
    } else {
      return this.event.subscribe(events, callback);
    }
  }

  // 订阅一次事件
  subscribeOnce(event, callback): void {
    this.event.subscribe(event, callback)
  }

  // 发布事件
  publish(event, ...args: any): any {
    return this.event.publish.apply(this.event, Array.prototype.slice.call(arguments));
  }

}
